<script setup lang="ts">
import EquipRequest from '@/request/equipRequest';
import useModal from '@/hooks/useModal';
import to from '@/utils/to';
import { useAppStore } from '@/store';
import validate, { IValidator } from '@/utils/validate';
import useToast from '@/hooks/useToast';
import { navigate } from '@/utils/navigate';

interface IProps {
  beeperCode: string;
  bindCallerInfo: IObtBindCallerInfoRes;
}

interface IState {
  show: boolean;
  communityList: { text: string; value: string }[];
  pickerTitle: string;
  placeList: ILocaleFewInfoRes[];
  params: {
    localeId?: number;
    installArea: string;
    localeNickName?: string;
    linkName?: string;
    phone?: string;
  };
}

type EmitEvents = {
  (event: 'submit', payload: { params: IState['params'] }): void;
};

const props = defineProps<IProps>();
const store = useAppStore();
const emits = defineEmits<EmitEvents>();
const state = reactive<IState>({ placeList: [], show: false, communityList: [], pickerTitle: '安装区域', params: { installArea: '', phone: store.$state.userInfo.phone || '' } });
const { showModal } = useModal();
const { showToast } = useToast();

const validators: IValidator<typeof state.params>[] = [
  { key: 'installArea', name: '安装区域', required: true },
  { key: 'phone', name: '联系人电话', required: true, rule: /^(?:\+86)?1[3-9]\d{9}$/ },
  { key: 'linkName', name: '联系人', required: true },
];

onMounted(() => {
  fetchObtainPlaceList();
});

// 获得场所列表
const fetchObtainPlaceList = () => {
  EquipRequest.LocaleList({ beeperId: props.bindCallerInfo.relationId }).then((res) => {
    state.placeList = res.data;
  });
};

// 点击弹窗层选项
const handlePickerCellClick = (title: '安装场所' | '安装区域') => {
  state.pickerTitle = title;
  if (title === '安装场所') {
    state.communityList = state.placeList.map((item) => {
      return { text: item.name, value: item.id.toString() };
    });
    state.communityList.push({ text: '自定义场所', value: '自定义安装场所' });
  }
  if (title === '安装区域') {
    state.communityList = ['客厅', '主卧', '次卧', '儿童房', '书房', '厨房', '阳台', '卫生间', '自定义安装区域'].map((item) => {
      return { text: item, value: item };
    });
  }
  state.show = true;
};

// 选择器选中事件
const handlePickerConfirm = async (event: any) => {
  if (state.pickerTitle === '安装场所') {
    const value = event.detail.value.value;
    if (value === `自定义安装场所`) {
      delete state.params.localeId;
      state.params.localeNickName = '';
      state.show = false;
      const [err, success] = await to(showModal('', { editable: true, showCancel: true }, `请输入自定义安装场所`));
      if (err) return;
      if (success.confirm) state.params.localeNickName = success.content;
    } else {
      state.params.localeNickName = '';
      state.params.localeId = Number(value);
    }
  }
  if (state.pickerTitle === '安装区域') {
    const value = event.detail.value.value;
    if (value === `自定义安装区域`) {
      state.show = false;
      const [err, success] = await to(showModal('', { editable: true, showCancel: true }, `请输入自定义安装区域`));
      if (err) return;
      if (success.confirm) state.params.installArea = success.content || '';
    } else {
      state.params.installArea = value;
    }
  }
  state.show = false;
};

// 绑定呼叫器
const handleBindBeeperClick = async () => {
  if (!state.params.localeNickName && !state.params.localeId) {
    showToast(`必填字段 安装场所 为空`);
    return;
  }
  const isValid = validate(state.params, validators);
  if (isValid) {
    const [err] = await to(EquipRequest.BindCallerDevice({ ...state.params, equipId: props.bindCallerInfo.equipId, hasLoading: true }));
    if (err) return;
    if (props.bindCallerInfo.equipType === 1) store.$patch({ beeperId: props.bindCallerInfo.relationId });
    showToast(props.bindCallerInfo.equipType === 1 ? '绑定呼叫器成功' : '绑定呼叫器成功,请等待主用户同意', props.bindCallerInfo.equipType === 1 ? 'success' : 'none').then(() => {
      setTimeout(() => {
        navigate({ url: '/pages/home/index', type: 'switchTab' });
      }, 1000);
    });
  }
};
</script>

<template>
  <view class="bg-white c-br c-pd py-12px mb-12px">
    <view class="fw-bold">安装信息</view>
    <van-divider />
    <van-cell title="安装场所" required is-link @click="handlePickerCellClick('安装场所')">
      <view :class="state.params.localeId || state.params.localeNickName ? 'c-color-black text-align-left' : 'c-text-color-grey text-align-left'">{{
        state.placeList.find((item) => item.id === state.params.localeId)?.name || state.params.localeNickName || '请选择安装场所'
      }}</view>
    </van-cell>
    <van-cell title="安装区域" required is-link @click="handlePickerCellClick('安装区域')">
      <view :class="state.params.installArea ? 'c-color-black text-align-left' : 'c-text-color-grey text-align-left'">{{ state.params.installArea || '请选择安装区域' }}</view>
    </van-cell>
    <van-field clearable clickable :value="state.params.linkName" label="联系人" placeholder="请输入联系人" required @change="state.params.linkName = $event.detail" />
    <van-field clearable clickable :value="state.params.phone" label="电话" placeholder="请输入联系人电话" required @change="state.params.phone = $event.detail" />
  </view>

  <view class="mt-12px">
    <van-button type="primary" :color="'#ffc300'" block @click="handleBindBeeperClick"> 绑定呼叫器 </van-button>
  </view>

  <van-popup position="bottom" round :show="state.show" @close="state.show = false">
    <view class="bg-white w-full">
      <van-picker show-toolbar value-key="text" :columns="state.communityList" :title="`请选择${state.pickerTitle}`" @cancel="state.show = false" @confirm="handlePickerConfirm" />
    </view>
  </van-popup>
</template>
